package com.gufe.service.admin.impl.joinArmy;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gufe.dto.adminJoinArmy.AddJoinArmyDTO;
import com.gufe.dto.adminJoinArmy.ArmyMemberDTO;
import com.gufe.dto.adminJoinArmy.JoinArmyInfoDTO;
import com.gufe.dto.adminJoinArmy.PageJoinArmyMemberDTO;
import com.gufe.entity.*;
import com.gufe.exception.EmptyFieldException;
import com.gufe.exception.NullDataException;
import com.gufe.exception.RollBackException;
import com.gufe.mapper.admin.allSchool.AllSchoolMapper;
import com.gufe.mapper.admin.joinArmy.JoinArmyMapper;
import com.gufe.mapper.admin.preReserve.PreReserveMemberMapper;
import com.gufe.mapper.admin.club.ActiveMemberMapper;
import com.gufe.result.PageResult;
import com.gufe.service.admin.joinArmy.JoinArmyService;
import com.gufe.utils.CustomDateUtil;
import com.gufe.utils.ImportExcelUtil;
import com.gufe.vo.allSchool.PhysicalTestVO;
import com.gufe.vo.joinArmy.JoinArmyPersonInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class JoinArmyServiceImpl implements JoinArmyService {

    @Autowired
    private JoinArmyMapper joinArmyMapper;
    @Autowired
    private PreReserveMemberMapper preReserveMemberMapper;
    @Autowired
    private ActiveMemberMapper activeMemberMapper;
    @Autowired
    private AllSchoolMapper allSchoolMapper;

    //分页查询入伍人员
    @Override
    public PageResult pageJoinArmyMember(PageJoinArmyMemberDTO pjamd) {
        PageHelper.startPage(pjamd.getPage(), pjamd.getPageSize());
        Page page = joinArmyMapper.pageJoinArmyMember(pjamd);
        return new PageResult(page.getTotal(), page.getResult());
    }

    //新增入伍成员
    @Override
    public void newJoinArmyMember(ArmyMemberDTO armyMemberDTO) {
        if (armyMemberDTO == null) {
            throw new NullDataException();
        }
        //得到userId
        Integer userId = preReserveMemberMapper.getUserIdByStudentId(armyMemberDTO.getStudentId());
        if (userId == null) {
            //表示没有使用小程序
            userId = -1;
        }
        ArmyMember armyMember = new ArmyMember();
        BeanUtils.copyProperties(armyMemberDTO, armyMember);
        armyMember.setUserId(userId);
        //得到年级
        String grade = armyMemberDTO.getStudentId().toString().substring(0, 4);
        armyMember.setGrade(Integer.valueOf(grade));
        //处理男女已婚
        armyMember.setGender("男".equals(armyMemberDTO.getGender()) ? 1 : 0);
        armyMember.setMaritalStatus("已婚".equals(armyMemberDTO.getMaritalStatus()) ? 1 : 0);

        joinArmyMapper.newJoinArmyMember(armyMember);
    }

    //将预征和或预储成员转为入伍成员
    @Override
    @Transactional//启用事务保证删除和新增同时完成
    public void addJoinArmyMember(AddJoinArmyDTO addJoinArmyDTO) {
        try {
            String studentId = addJoinArmyDTO.getJoinArmyInfoDTO().getStudentId();
            //预储
            if ("preReserve".equals(addJoinArmyDTO.getType())) {
                //得到userId
                Integer userId = preReserveMemberMapper.getUserIdByStudentId(studentId);
                if (userId == null) {
                    throw new RuntimeException("预储成员不存在");
                }
                //删除预储成员
                preReserveMemberMapper.deletBasic(userId);
                preReserveMemberMapper.deleteMilitary(userId);
                preReserveMemberMapper.deletePreEnlistment(userId);
                preReserveMemberMapper.deleteStudyExperience(userId);
            }
            //预征班
            else {
                //删除预征班成员
                activeMemberMapper.deleteByStudentId(studentId);
            }

            ArmyMemberDTO joinArmyInfoDTO = addJoinArmyDTO.getJoinArmyInfoDTO();
            ArmyMember armyMember = new ArmyMember();
            BeanUtils.copyProperties(joinArmyInfoDTO, armyMember);

            armyMember.setGender("男".equals(joinArmyInfoDTO.getGender()) ? 1 : 0);
            armyMember.setMaritalStatus("已婚".equals(joinArmyInfoDTO.getMaritalStatus()) ? 1 : 0);

            //添加到入伍
            joinArmyMapper.newJoinArmyMember(armyMember);
        } catch (Exception e) {
            // 手动触发回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            // 返回自定义错误信息
            throw new RollBackException("事务回滚：" + e.getMessage());
        }
    }


    //从预储预征班查询入伍人员信息
    @Override
    public List<ArmyMember> getJoinArmyInfo(JoinArmyInfoDTO jaid) {
        String[] studentIds = jaid.getStudentIds();
        List<ArmyMember> list = new ArrayList<ArmyMember>();
        //预储成员
        if ("preReserve".equals(jaid.getType())) {
            for (String studentId : studentIds) {
                ArmyMember armyMember = new ArmyMember();
                Integer userId = preReserveMemberMapper.getUserIdByStudentId(studentId);
                BasicInfo basicInfo = preReserveMemberMapper.getBasicInfo(userId);
                MilitaryInfo militaryInfo = preReserveMemberMapper.getMilitaryInfo(userId);
                BeanUtils.copyProperties(basicInfo, armyMember);
                BeanUtils.copyProperties(militaryInfo, armyMember);
                list.add(armyMember);
            }
        }
        //预征班成员
        else {
            for (String studentId : studentIds) {
                ArmyMember armyMember = new ArmyMember();
                //获取社团成员详细信息
                PrecollectMember precollectMember = activeMemberMapper.getPrecollectMemberBystudentId(studentId);
                BeanUtils.copyProperties(precollectMember, armyMember);
                //处理名称不一样的项
                armyMember.setProfilePicture(precollectMember.getImgUrl());//处理照片
                armyMember.setTelephone(precollectMember.getContactNumber());//处理电话
                armyMember.setGender(Integer.valueOf(precollectMember.getGender()));//处理性别

                list.add(armyMember);
            }
        }
        return list;
    }

    public String importArmyData(MultipartFile file) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<ArmyMember> armyMemberList = new ArrayList<>();

        //验证文件类型
        if (!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xls") && !file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xlsx")) {
            return "文件类型有误！请上传Excle文件";
        }
        //获取数据
        List<List<Object>> olist = null;
        try {
            olist = ImportExcelUtil.getListByExcel(file.getInputStream(), file.getOriginalFilename());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //封装数据
        for (int i = 0; i < olist.size(); i++) {
            List<Object> list = olist.get(i);
            // 跳过标题行
            if (list.get(0) == "" || ("序号").equals(list.get(0))) {
                continue;
            }
            ArmyMember armyMember = new ArmyMember();
            //根据下标获取每一行的每一条数据
            if (String.valueOf(list.get(1)) == null || String.valueOf(list.get(1)).isEmpty()) {
                throw new EmptyFieldException("姓名不能为空!!!");
            }
            armyMember.setName(String.valueOf(list.get(1)));


            if (String.valueOf(list.get(2)) == null || String.valueOf(list.get(2)).equals("")) {
                return "性别不能为空";
            }
            String genderStr = String.valueOf(list.get(2)).trim();
            int gender = "男".equals(genderStr) ? 1 : ("女".equals(genderStr) ? 2 : 0);
            armyMember.setGender(gender);


            if (String.valueOf(list.get(3)) == null || String.valueOf(list.get(3)).equals("")) {
                return "身份证号不能为空";
            }
            armyMember.setIdCard(String.valueOf(list.get(3)));

            String nationality = String.valueOf(list.get(4)).trim(); // 修改索引为4
            armyMember.setNationality(nationality.isEmpty() ? null : nationality);

            // 政治面貌
            String politicalAffiliation = String.valueOf(list.get(5)).trim(); // 修改索引为5
            armyMember.setPoliticalAffiliation(politicalAffiliation.isEmpty() ? null : politicalAffiliation);

            // 学历
            String educationLevel = String.valueOf(list.get(6)).trim();
            armyMember.setEducationBackground(educationLevel.isEmpty() ? null : educationLevel);

            // 学籍状态
            String academicStatus = String.valueOf(list.get(7)).trim();
            armyMember.setSchoolStatus(academicStatus.isEmpty() ? null : academicStatus);

            // 学院
            String college = String.valueOf(list.get(8)).trim();
            armyMember.setCollege(college.isEmpty() ? null : college);

            // 专业
            String major = String.valueOf(list.get(9)).trim();
            armyMember.setMajor(major.isEmpty() ? null : major);

            // 学号
            String studentId = String.valueOf(list.get(10)).trim();
            armyMember.setStudentId(studentId.isEmpty() ? null : studentId);

            // 家庭地址
            String familyAddress = String.valueOf(list.get(11)).trim();
            armyMember.setHomeAddress(familyAddress.isEmpty() ? null : familyAddress);

            // 联系电话
            String telephone = String.valueOf(list.get(12)).trim();
            armyMember.setTelephone(telephone.isEmpty() ? null : telephone);

            // 入伍地点
            String enlistmentPlace = String.valueOf(list.get(13)).trim();
            armyMember.setJoinArmyPlace(enlistmentPlace.isEmpty() ? null : enlistmentPlace);

            // 入伍日期处理
            String enlistmentDateInput = String.valueOf(list.get(14)).trim();
            try {
                String enlistmentDate = CustomDateUtil.parsePartialDate(enlistmentDateInput);
                armyMember.setJoinArmyDate(LocalDate.parse(enlistmentDate));
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("第 " + (i + 1) + " 行入伍日期错误: " + e.getMessage());
            }

            // 退伍日期处理
            String dischargeDateInput = String.valueOf(list.get(15)).trim();
            try {
                String dischargeDate = CustomDateUtil.parsePartialDate(dischargeDateInput);
                armyMember.setDischargeDate(LocalDate.parse(dischargeDate));
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("第 " + (i + 1) + " 行退伍日期错误: " + e.getMessage());
            }

            // 兵种
            String armClass = String.valueOf(list.get(16)).trim();
            armyMember.setMilitaryBranch(armClass.isEmpty() ? null : armClass);

            // 是否留队
            String isServingStr = String.valueOf(list.get(17)).trim();
            armyMember.setRetentionArmyStatus(isServingStr.isEmpty() ? null : isServingStr);


            // 是否立功受奖
            String hasMeritorious = String.valueOf(list.get(18)).trim();
            armyMember.setTroopAwards(hasMeritorious.isEmpty() ? null : hasMeritorious);

            // 备注
            String remark = String.valueOf(list.get(19)).trim();
            armyMember.setRemark(remark.isEmpty() ? null : remark);


            armyMemberList.add(armyMember);
        }

        // 将Excel中的数据插入数据库
        int i = joinArmyMapper.insertArmyMember(armyMemberList);
        if (i != 0) {
            System.out.println("数据插入成功！！！");
        } else {
            return "文档内无数据，请重新导入";
        }


        return "数据插入成功";
    }


    //获取个人详细信息
    @Override
    public JoinArmyPersonInfoVO getPersonDetailInfo(String id) {

        //获取基础数据
        ArmyMember armyMember = joinArmyMapper.getArmyPersonBasicInfo(id);


        //获取体测数据
        List<PhysicalTestVO> physicalTestVOList = new ArrayList<>();
        if (armyMember.getStudentId() != null) {
            //学号存在才获取
            physicalTestVOList = allSchoolMapper.getPhysicalTestVOs(armyMember.getStudentId());
        }

        JoinArmyPersonInfoVO joinArmyPersonInfoVO = new JoinArmyPersonInfoVO();

        BeanUtils.copyProperties(armyMember, joinArmyPersonInfoVO);
        joinArmyPersonInfoVO.setPhysicalTestVOList(physicalTestVOList);

        return joinArmyPersonInfoVO;
    }


}
